package com.doyens.seckill.timer;

import com.doyens.seckill.mapper.SeckillGoodsMapper;
import com.doyens.seckill.pojo.SeckillGoods;
import com.doyens.seckill.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
public class SeckillGoodsTask {

    @Autowired
    private SeckillGoodsMapper  seckillGoodsMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Scheduled(cron = "0/15 * * * * ?")
    public void loadGoods(){
     //   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     //   System.out.println(simpleDateFormat.format(new Date())+"===============");


        //1.查询出所有的时间区域
        List<Date> dateMenus = DateUtil.getDateMenus();
        //2.循环时间区域,查询每个时间区域的秒杀商品
        for (Date startTime : dateMenus) {
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            //2.1 商品必须是审核通过
            criteria.andEqualTo("status","1");
            //2.2 库存 > 0;
            criteria.andGreaterThan("stockCount",0);
            //2.3 秒杀开始时间 >= 当前循环的时间区间的开始时间
            criteria.andGreaterThanOrEqualTo("startTime",startTime);
            //2.4 秒杀结束时间< 当前时间的区间的 + 两小时
            criteria.andLessThan("endTime",DateUtil.addDateHour(startTime,2));
            //过滤查询
            //select * from tables  where in not in (123,342,121,12)
            Set keys = redisTemplate.boundHashOps("seckillGoods_" + DateUtil.date2Str(startTime)).keys();
            if (keys !=null && keys.size()>0){
                criteria.andNotIn("id",keys);
            }
            //2.5执行查询
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);
            //3.将秒杀商品存入到redis中
            for (SeckillGoods seckillGood : seckillGoods) {
                redisTemplate.boundHashOps("seckillGoods_"+DateUtil.date2Str(startTime)).put(seckillGood.getId(),seckillGood);
            }
        }




    }
}
